package com.syqc.choose.car

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.entity.CarLick
import com.syqc.entity.KeyWords
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject

/**
 *@Author Jasper
 *@Time   2020/7/22
 *@Desc   搜索车辆
 */
class SearchViewModel : AutoDisposeViewModel() {
    private val searchWords =
        CacheMMKV.decodeParcelable("search_word", KeyWords::class.java) ?: KeyWords()

    //搜素车辆条件  1 车牌   2.终端号  3 SIM 卡   4.终端标识
    var type:Int=0

    val changeTeamLive = MutableLiveData<Int>()

    private val wordsObservable by lazy {
        BehaviorSubject.create<List<String>>()
    }

    val searchSub: PublishSubject<MutableList<CarLick>> by lazy {
        PublishSubject.create<MutableList<CarLick>>()
    }

    fun wordsObserver(): Observable<List<String>> {
        return wordsObservable.hide()
    }

    init {
        wordsObservable.onNext(searchWords.words)
    }


    fun searchCars(plate: String = "", video: Boolean = false) {
        if (plate.isEmpty()) {
            toast(R.string.toast_hint_search_car)
            return
        }

        if (!isHasWord(plate)) {
            searchWords.words.add(plate)
            wordsObservable.onNext(searchWords.words)
            CacheMMKV.encodeParcelable("search_word", searchWords)
        }
        toastLoading(true)
        ServiceHelper.getRepository().getSearchCar(plate,"${type+1}",video = video).autoDispose(this)
            .subscribe({
                if (it.isNullOrEmpty()) {
                    toast(R.string.desc_no_search_car)
                }
                searchSub.onNext(it)
                toastLoading(false)
            }, error)
    }

    private fun isHasWord(plate: String): Boolean {
        for (word in searchWords.words) {
            if (plate == word) return true
        }
        return false
    }

    fun clear() {
        if (searchWords.words.isNullOrEmpty()) return
        searchWords.words.clear()
        wordsObservable.onNext(searchWords.words)
        CacheMMKV.encodeParcelable("search_word", searchWords)
    }


    /**
     * Change team  切换车队
     *
     * @param carId
     */
    fun changeTeam(carId: String) {
        ServiceHelper.getRepository().canChangeTeam(carId).autoDispose(this).subscribe({
            if (it.moditeam){
                changeTeamLive.postValue(1)
            }else{
                changeTeamLive.postValue(0)
            }
        }, {
            changeTeamLive.postValue(-1)
        })
    }
}

